package org.xiaojl.common.controller;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.xiaojl.common.Constants;
import org.xiaojl.common.base.BaseController;
import org.xiaojl.config.shiro.captcha.DreamCaptcha;
import org.xiaojl.utils.ToolUtil;

@Controller
public class CommonsController extends BaseController{
	private static final Logger log = LoggerFactory.getLogger(CommonsController.class);
	@Autowired
    private DreamCaptcha dreamCaptcha;
	
	 /**
     * 图形验证码
     */
    @RequestMapping("captcha.jpg")
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        dreamCaptcha.generate(request, response);
    }
    
    /**
	 * 转到文件上传页面 .
	 */
	@RequestMapping("/uploadifyUI")
	public ModelAndView addUI(Model model) {
		try {
			return operatePage("sys/w_uploadify",model);
		} catch (Exception e) {
			log.error("进入页面出现异常:", e);
			return operateError("获取数据失败");
		}
	}
    
    /**
     * 实现SpringMVC+servlet3.0文件上传功能:multipartResolver
     * 
     * <form method="post" enctype="multipart/form-data">  
        	选择要上传的文件：<input type="file" name="file" size="60" /><br/>  
       		<input type="submit" value="开始上传" />
       </form>  
       
     */
    @RequestMapping("/upload")  
    public @ResponseBody Object upload(HttpServletRequest request, 
    		HttpServletResponse response,  @RequestParam Map<String, Object> p)  
            throws ServletException, IOException {  
        try {
			// 获取 web application的绝对路径  
			String appPath = request.getServletContext().getRealPath("");  
			// 构造文件存放的路径  
			String savePath = appPath + File.separator + Constants.UPLOAD_PATH;  
			// 如果文件存放路径不存在，则mkdir一个  
			File fileSaveDir = new File(savePath);  
			if (!fileSaveDir.exists()) {  
			    fileSaveDir.mkdir();  
			}  
			StringBuffer buffer = new StringBuffer("");
			//request.getParts()用来获取multipart，其中就包括文件
			for (Part part : request.getParts()) {  
			    String fileName = extractFileName(part);  
			    if(ToolUtil.isNotEmpty(fileName)){  
			    	//当前上传文件的文件后缀
			        String suffix = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf("."),fileName.length()) : null;
			        String newFileName = ToolUtil.getUid()+suffix;
			        buffer.append(fileName+"#"+newFileName).append(",");
			        part.write(savePath + File.separator + newFileName);  
			    }  
			}  
			return renderResult(true,"文件上传成功",buffer.toString());
		} catch (Exception e) {
			log.error("文件上传失败", e);
			return renderResult(false,"文件上传失败",null);
		}
    }  
    
    /** 
     * 从content-disposition头中获取源文件名 
     * 	content-disposition头的格式如下： 
     * 		form-data; name="dataFile"; filename="PHOTO.JPG" 
     */  
    private String extractFileName(Part part) {  
        String contentDisp = part.getHeader("content-disposition");  
        String[] items = contentDisp.split(";");  
        for (String s : items) {  
            if (s.trim().startsWith("filename")) {  
                return s.substring(s.indexOf("=") + 2, s.length()-1);  
            }  
        }  
        return "";  
    }  
    
}
